package com.xul.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.xul.srb.core.mapper.DictMapper;
import com.xul.srb.core.pojo.dto.ExcelDictDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xul
 * @create 2021-11-09 23:22
 */
@Slf4j
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDTO> {

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<ExcelDictDTO> dictDTOList = new ArrayList<>();

    private DictMapper dictMapper;

    /**
     * 通过构造函数将dictMapper注入进来
     *
     * @param dictMapper
     */
    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    public ExcelDictDtoListener() {

    }

    /**
     * 每一条数据解析都会被调用
     *
     * @param excelDictDTO
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", excelDictDTO);
        dictDTOList.add(excelDictDTO);
        if (dictDTOList.size() >= BATCH_COUNT) {
            saveData(dictDTOList);
            dictDTOList.clear();
        }
    }

    private void saveData(List<ExcelDictDTO> dictDTOList) {
        log.info("{}条数据,开始存储数据库! " + dictDTOList.size());
        dictMapper.insertBatch(dictDTOList);
        log.info("{}条数据,开始存储数据库成功! " + dictDTOList.size());
    }

    /**
     * 所有数据解析完成 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 不足BATCH_COUNT的条数的批量保存
        saveData(dictDTOList);
        log.info("所以数据解析完成!");
    }
}
